import { defineStore } from 'pinia'
import api from '@/api'
import { setCookie, removeCookie } from '@/utils/cookie'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    userInfo: null,
    // 认证token
    token: null,
    // 登录状态
    isLoggedIn: false,
    // 加载状态
    isLoading: false
  }),

  getters: {
    // 获取用户ID
    userId: (state) => state.userInfo?.user_id,
    
    // 获取用户邮箱
    userEmail: (state) => state.userInfo?.email,
    
    // 获取用户名
    username: (state) => state.userInfo?.username,
    
    // 检查是否已登录
    isAuthenticated: (state) => !!(state.token && state.userInfo && state.isLoggedIn)
  },

  actions: {
    /**
     * 登录
     */
    async login(credentials) {
      console.log('🔐 [UserStore] 开始登录...')
      this.isLoading = true
      
      try {
        const response = await api.login(credentials)
        
        if (response.success) {
          console.log('✅ [UserStore] 登录成功')

          // 保存认证信息
          this.token = response.data.access_token
          this.userInfo = response.data.user || {
            user_id: response.data.user_id,
            email: credentials.email
          }
          this.isLoggedIn = true

          // 同时保存token到cookie中，确保streamChat等直接使用fetch的API能够获取到token
          if (this.token) {
            setCookie('token', this.token, 7) // 保存7天
            console.log('🍪 [UserStore] Token已保存到Cookie')
          }

          console.log('💾 [UserStore] 用户状态已保存:', {
            userId: this.userId,
            email: this.userEmail,
            hasToken: !!this.token
          })

          return { success: true, data: response.data }
        } else {
          console.error('❌ [UserStore] 登录失败:', response.message)
          return { success: false, message: response.message }
        }
      } catch (error) {
        console.error('❌ [UserStore] 登录异常:', error)
        return { 
          success: false, 
          message: error.response?.data?.detail || error.message || '登录失败' 
        }
      } finally {
        this.isLoading = false
      }
    },

    /**
     * 登出
     */
    logout() {
      console.log('🚪 [UserStore] 用户登出')

      // 清除状态
      this.token = null
      this.userInfo = null
      this.isLoggedIn = false

      // 同时清除cookie中的token
      removeCookie('token')
      console.log('🍪 [UserStore] Token已从Cookie中清除')

      console.log('🧹 [UserStore] 用户状态已清除')
    },

    /**
     * 验证并恢复登录状态
     */
    async validateAndRestoreAuth() {
      console.log('🔍 [UserStore] 验证并恢复登录状态...')
      
      // 如果没有token，直接返回
      if (!this.token) {
        console.log('⚠️ [UserStore] 没有token，无法恢复登录状态')
        return false
      }
      
      this.isLoading = true
      
      try {
        // 验证token是否仍然有效
        console.log('🔍 [UserStore] 验证token有效性...')
        const response = await api.getCurrentUser()
        
        if (response.success && response.data) {
          console.log('✅ [UserStore] Token验证成功，恢复登录状态')
          
          // 更新用户信息
          this.userInfo = response.data
          this.isLoggedIn = true
          
          console.log('💾 [UserStore] 登录状态已恢复:', {
            userId: this.userId,
            email: this.userEmail
          })
          
          return true
        } else {
          console.log('❌ [UserStore] Token验证失败，清除登录状态')
          this.logout()
          return false
        }
      } catch (error) {
        console.error('❌ [UserStore] Token验证异常:', error)
        
        // 如果是401错误，说明token过期
        if (error.response?.status === 401) {
          console.log('🔒 [UserStore] Token已过期，清除登录状态')
          this.logout()
        }
        
        return false
      } finally {
        this.isLoading = false
      }
    },

    /**
     * 更新用户信息
     */
    updateUserInfo(userInfo) {
      console.log('📝 [UserStore] 更新用户信息')
      this.userInfo = { ...this.userInfo, ...userInfo }
    },

    /**
     * 设置加载状态
     */
    setLoading(loading) {
      this.isLoading = loading
    }
  },

  // 持久化配置
  persist: {
    // 使用 localStorage 存储
    storage: localStorage,
    // 只持久化这些字段
    paths: ['userInfo', 'token', 'isLoggedIn'],
    // 自定义序列化
    serializer: {
      serialize: JSON.stringify,
      deserialize: JSON.parse
    },
    // 在恢复状态前的钩子
    beforeRestore: (context) => {
      console.log('🔄 [UserStore] 正在从localStorage恢复状态...')
    },
    // 在恢复状态后的钩子
    afterRestore: (context) => {
      console.log('✅ [UserStore] 状态恢复完成:', {
        hasToken: !!context.store.token,
        hasUserInfo: !!context.store.userInfo,
        isLoggedIn: context.store.isLoggedIn
      })
    }
  }
})
